// Provide an XML object to send a query
function getXMLHttpRequest()
{
	var xhr = null;
	
	if (window.XMLHttpRequest || window.ActiveXObject)
	{
		if (window.ActiveXObject)
		{
			try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); }
			catch(e) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); }
		} else { xhr = new XMLHttpRequest(); }
	}
	else { alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest..."); return null; }
	
	return xhr;
}

// send a query to the server and return the collected data
// parameters :
// - page : the page to be called
// - parameters : the parametre to be send to the page. Muse be like 'var1=value1&var2=value2&...', such as a GET parameters
// - type : the type of the request, must be 'GET' or 'POST' (POST support longers parameters)
function sendQuery(page, parameters, type)
{
	var xhr = getXMLHttpRequest();
	var requetePage = "ajax.php";
	
	if (type == undefined)
	{
		type = "POST";
	}
	
	if (type == "GET")
	{
		xhr.open("GET",  page + "?" + parameters, false);
		xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		xhr.send(null);
	}
	else if (type == "POST")
	{
		xhr.open("POST", page, false);
		xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		xhr.send(parameters);
	}
	
	return xhr.responseText;
}

/* Send a query to the server. The result of the query must be JSON data which will be parsed and then returned. */
/* output data :
out.success => boolean which mean if the query was a success
out.result => result of the JSON parsing
*/
function sendQueryJSON(page, parametre, typeRequete)
{
	var s = sendQuery(page, parametre, typeRequete);
	try
	{
		var r = eval('(' + s + ')');
		return r;
	}
	catch(e)
	{
		alert("Error in JSON parsing :\n" + s);
	}
}

/* Send a query to the server. The result of the query must be JSON data which will be parsed and then returned. */
/* output data :
out.success => boolean which mean if the query was a success
out.result => result of the JSON parsing
*/
function sendConstructedQueryJSON(page, parametre, typeRequete)
{
	function paramToString(s, prefix, firstCall) {
		if(s == undefined) s = '';
		var r = "";
		
		if(firstCall == undefined) firstCall = true;
		if(prefix == undefined) prefix = "";
		
		if(typeof(s) == 'object' || s.constructor == Array) {
			var first = true;
			for (var k in s) {
				if(first) first = false; else r += '&';
				if(firstCall) r += paramToString(s[k], prefix + k, false);
				else r += paramToString(s[k], prefix + "["+k+"]", false);
			}
		}
		else r = prefix + "=" + s;
		
		return r;
	}
	
	var s = sendQuery(page, paramToString(parametre), typeRequete);
	try
	{
		var r = eval('(' + s + ')');
		return r;
	}
	catch(e)
	{
		alert("Error in JSON parsing :\n" + s);
	}
}
